package com.lagou.session;

import com.lagou.pojo.Configuration;
import com.lagou.transaction.JdbcTransaction;
import com.lagou.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.SQLException;

public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }


    @Override
    public SqlSession openSession() {
        return this.openSessionFromDataSource("simple",false);
    }

    @Override
    public SqlSession openSession(boolean autoCommit) {
        return this.openSessionFromDataSource("simple",autoCommit);
    }

    private SqlSession openSessionFromDataSource(String execType, boolean autoCommit) {
        Transaction tx = null;
        DefaultSqlSession sqlSession = null;
        try {
            DataSource dataSource = this.configuration.getDataSource();
            tx = new JdbcTransaction(dataSource,autoCommit);
            Executor executor = this.configuration.newExecutor(tx, execType);
            sqlSession = new DefaultSqlSession(this.configuration, executor, autoCommit);
        } catch (Exception e) {
            this.closeTransaction(tx);
            e.printStackTrace();
        }
        return sqlSession;
    }

    private void closeTransaction(Transaction tx) {
        if (tx != null) {
            try {
                tx.close();
            } catch (SQLException var3) {
            }
        }

    }
}
